package pdd;

import com.alibaba.fastjson.JSONObject;
import com.openJar.responses.PddAuthInfoResponse;
import com.shigu.beans.vo.AuthedInfo;
import com.shigu.component.common.InnerResponse;
import com.shigu.servicies.AsynService;
import com.shigu.servicies.PddAuthService;
import com.shigu.tools.JsonResponseUtil;
import com.sun.org.apache.bcel.internal.generic.IFNE;
import com.utils.publics.Opt3Des;
import net.sf.json.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Created by gtx on 2018/6/5.
 * 授权
 * @author gtx
 * @description
 * @since 0.0.1
 */
@Controller
@RequestMapping("xzp")
public class AuthAction {

    @Resource
    private PddAuthService authService;

    @Resource
    private AsynService asynService;

    /**
     * 拼多多登陆回调
     * @param code
     * @param state
     * @return
     */
    @RequestMapping("callback")
    public String callback(String code, String state){
        if (StringUtils.isBlank(code) || StringUtils.isBlank(state)) {
            return "redirect:http://www.571xz.com";
        }

        InnerResponse<AuthedInfo> response = authService.getAuthedInfo(code);
        if (!response.hasSuccess()) {//授权失败
            //授权失败页
            return "auth-failure";
        }
        AuthedInfo authedInfo = response.getData();

        //同步店内类目
        boolean flag = authService.shouldUpdateShopCat(authedInfo.getThirdUid());
        if (flag) {
            asynService.updateShopCatAsync(authedInfo.getThirdUid());
        }
        PddAuthInfoResponse pddAuthInfoResponse = new PddAuthInfoResponse();
        pddAuthInfoResponse.setSuccess(true);
        pddAuthInfoResponse.setThirdUid(authedInfo.getThirdUid());
        pddAuthInfoResponse.setThirdUserNick(authedInfo.getThirdUserNick());
        pddAuthInfoResponse.setAccessToken(authedInfo.getAccessToken());
        pddAuthInfoResponse.setRefreshToken(authedInfo.getRefreshToken());
//        pddAuthInfoResponse.setAuthScope(JSONObject.toJSONString(authedInfo.getAuthScope()));
        pddAuthInfoResponse.setAuthTime(authedInfo.getAuthTime());
        pddAuthInfoResponse.setExpiresIn(authedInfo.getExpiresIn());

        String jsonString = JSONObject.toJSONString(pddAuthInfoResponse);
        String encryptPlainData = Opt3Des.encryptPlainData(jsonString);//加密
        return "redirect:http://www.571xz.com/pdd/callback.htm?code="+encryptPlainData;
    }


}
